﻿using System;
using JamesZhao.Engine.Graphics.Effects;
using JamesZhao.Engine.Graphics.Geometry;
using JamesZhao.Engine.Graphics.Surfaces;
using JamesZhao.Engine.Graphics.Visuals;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;

namespace JamesZhao.Engine.Graphics.RenderStages
{
    public class SteeringSolveStage : RenderStage
    {
        public ColorSurface SceneDepth { get; set; }
        public ColorSurface SolveResult { get; set; }

        public SteeringSolveStage(GraphicsDevice device)
        {
            SolveEffect = new GpuProgram(device, "Shaders/Steering/Solve.fx");


            var quadGeom = new GeometryBuffer(device);
            quadGeom.InitializeFrom(MeshData.LoadFullScreenQuad());
            FullScreenQuad = new MeshDrawable
            {
                GeometryBuffer = quadGeom
            };
        }

        protected MeshDrawable FullScreenQuad { get; set; }

        protected GpuProgram SolveEffect { get; set; }

        public override string Name
        {
            get { return "Steering Solve"; }
        }

        protected override void OnRender(GraphicsDevice device, SwapChain swapChain, VisualsList visualsList, Camera camera)
        {
            device.ImmediateContext.ClearRenderTargetView(SolveResult.TargetView, new Color4(0, 0, 0, 0));

            device.ImmediateContext.OutputMerger.SetTargets(
                new[]
                    {
                        SolveResult.TargetView
                    });

            SolveEffect.ScalarVariables["zFar"].Set(camera.Lens.Far);
            SolveEffect.VectorVariables["screenSize"].Set(new Vector2(SceneDepth.ActualSize.Width,
                                                                                 SceneDepth.ActualSize.Height));

            SolveEffect.ResourceVariables["depthTexture"].SetResource(SceneDepth.ResourceView);

            device.ImmediateContext.OutputMerger.SetTargets(SolveResult.TargetView);
            FullScreenQuad.RenderWithGpuProgram(device, camera, SolveEffect);
        }
    }
}
